package fr.glre.tartopom;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.PowerManager;
import android.os.Vibrator;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class RestaplatActivity extends Activity implements SensorEventListener {

	private TextView tv;
	private Button bouton;

	private SensorManager sm;
	private Handler handler321;
	private int compteur;

	private float x;
	private float startX;
	private boolean wasInPrecisionZone;
	private double nbTour;
	private double limitePrecision = 40;
	private boolean isStarted;

	private MediaPlayer mp;
	private PowerManager pm;
	PowerManager.WakeLock wl;

	private Runnable troisdeuxungo = new Runnable() {
		@Override
		public void run() {
			if (compteur != 0) {
				tv.setText("" + compteur);
				compteur--;

				handler321.postDelayed(this, 1000);
			} else {
				tv.setText("Tournez !");
				start();
			}
		}
	};

	public float getStartX() {
		return startX;
	}

	public float getX() {
		return x;
	}

	private void lost() {
		double nbTours = nbTour;
		isStarted = false;

		tv.setText("Vous avez perdu !\nVous avez réussi à faire "
				+ Math.round(nbTours * 100.) / 100. + " tours.");

		bouton.setVisibility(Button.VISIBLE);
	}

	@Override
	public void onAccuracyChanged(Sensor arg0, int arg1) {
		// TODO Auto-generated method stub
	}

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.restaplat);

		sm = (SensorManager) getSystemService(SENSOR_SERVICE);
		sm.registerListener(this, sm.getDefaultSensor(Sensor.TYPE_ORIENTATION),
				SensorManager.SENSOR_DELAY_GAME);

		pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
		wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "resteaplat");
		wl.acquire();

		tv = (TextView) findViewById(R.id.tvplat1);
		bouton = (Button) findViewById(R.id.bplat);

		tv.setText("Quand vous serez prêts, appuyez sur le bouton.");

		mp = MediaPlayer.create(getBaseContext(), R.raw.son);

		bouton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				bouton.setVisibility(Button.INVISIBLE);

				tv.setText("3");
				handler321 = new Handler();
				compteur = 2;
				handler321.postDelayed(troisdeuxungo, 1000);
			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.restaplatmenu, menu);

		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		switch (item.getItemId()) {
		case R.id.item1:
			Intent intent = new Intent(this.getBaseContext(),
					TournePomActivity.class);
			startActivity(intent);
			finish();
			break;
		case R.id.item2:
			Toast.makeText(
					this,
					"Posez le téléphone à plat sur votre main,"
							+ " et appuyez sur le bouton \"C\'est parti !\". "
							+ "Vous devez faire tourner le téléphone en le "
							+ "laissant le plus à plat possible dans votre"
							+ "main. Essayez de faire le plus de tours possible !",
					Toast.LENGTH_LONG).show();
			break;
		case R.id.item4:
			System.exit(RESULT_OK);
			break;
		case R.id.item5:
			limitePrecision = 40;
			break;
		case R.id.item6:
			limitePrecision = 30;
			break;
		case R.id.item7:
			limitePrecision = 20;
			break;
		case R.id.item8:
			limitePrecision = 10;
			break;
		case R.id.item9:
			limitePrecision = 5;
			break;
		}

		return false;
	}

	@Override
	public void onPause() {
		super.onPause();
		wl.release();
		sm.unregisterListener(this);
	}

	@Override
	public void onResume() {
		super.onResume();
		wl.acquire();
		sm.registerListener(this, sm.getDefaultSensor(Sensor.TYPE_ORIENTATION),
				SensorManager.SENSOR_DELAY_GAME);
	}

	@Override
	public void onSensorChanged(SensorEvent event) {
		int sensor = event.sensor.getType();
		float[] values = event.values;
		float platX = 0;
		float platY = 0;

		synchronized (this) {
			if (sensor == Sensor.TYPE_ORIENTATION) {
				setX(values[0]);
				platX = Math.abs(values[1]);
				platY = Math.abs(values[2]);
			}
		}

		if (isStarted
				&& (platX > limitePrecision * 0.7 || platY > limitePrecision * 0.7)) {
			mp.start();
		}
		if (isStarted
				&& (platX > limitePrecision * 0.8 || platY > limitePrecision * 0.8)) {
			mp.start();
			mp.start();
		}
		if (isStarted
				&& (platX > limitePrecision * 0.9 || platY > limitePrecision * 0.9)) {
			mp.start();
			mp.start();
			mp.start();
		}
		if (isStarted && (platX > limitePrecision || platY > limitePrecision)) {
			((Vibrator) getSystemService(Context.VIBRATOR_SERVICE))
					.vibrate(1500);
			lost();
		} else {
			nbTour = Math.floor(nbTour);
			if ((this.getX() > this.getStartX())
					&& (this.getX() < this.getStartX() + 5)) {
				if (!wasInPrecisionZone) {
					nbTour = nbTour + 1;
				}

				wasInPrecisionZone = true;
			} else {
				wasInPrecisionZone = false;
			}

			double decallage = ((this.getStartX() - this.getX()) / 360.);

			if (decallage < 0) {
				decallage = decallage + 1.;
			}

			nbTour = nbTour + decallage;
		}
	}

	public void setStartX(float startX) {
		this.startX = startX;
	}

	public void setX(float x) {
		this.x = x;
	}

	public void start() {
		setStartX(getX());
		wasInPrecisionZone = true;
		nbTour = 0;
		isStarted = true;
	}
}
